#include <stdio.h>
#include <string.h>
#include "../stack/array_stack.h"

#define N 20

int oper_cmp(char src, char tar);
char *strrev(char *str);
int stack_peek(astack_t *s, char *tmp);

int main(int argc, char *argv[])
{
    astack_t *in = NULL, *out = NULL;
    int ret;
    char tmp, stmp;

    if (argc < 2)
        return -1;

    ret = astack_init(&in, N, sizeof(char));
    if (ret != 0) {
        printf("init err\n");
        return -1;
    }
    ret = astack_init(&out, N, sizeof(char));
    if (ret != 0) {
        printf("init err\n");
        return -1;
    }

    argv[1] = strrev(argv[1]);
    printf("%s\n", argv[1]);

    for (ret = 0; argv[1][ret] != '\0'; ret++) {
        tmp = argv[1][ret];

        if (')' == tmp) {
            astack_push(in, &tmp);
        } else if ('(' == tmp) {
            while (!astack_empty(in)){
                astack_pop(in, &stmp);
                if (stmp != '(' && stmp != ')')
                    astack_push(out, &stmp);
                if (')' == stmp)
                    break;
            }
        } else if (tmp >= 'a' && tmp <= 'z') {
            astack_push(out, &tmp);
        } else {
            while (!astack_empty(in)) {
                stack_peek(in, &stmp);
                if (')' == stmp)
                    break;

                if (oper_cmp(stmp, tmp) == 1) {
                    astack_pop(in, &stmp);
                    astack_push(out, &stmp);
                } else {
                    break;
                }
            }
            astack_push(in, &tmp);
        }
    }

    while (!astack_empty(in)) {
        astack_pop(in, &stmp);
        astack_push(out, &stmp);
    }

    while (!astack_empty(out)) {
        astack_pop(out, &stmp);
        printf("%c", stmp);
    }
    printf("\n");

    return 0;
}


// 比较运算符的优先级 src > tar return 1
int oper_cmp(char src, char tar)
{
    if (src == tar)
        return 0;
    if ('*' == src || '/' == src)
        return '+' == tar || '-' == tar;

    if ('*' == src || '/' == src) {
        if ('*' == tar || '/' == tar)
            return 0;
    }

    if ('-' == src || '+' == src)
        return -1;
}

char *strrev(char *str)
{
    if (!str)
        return NULL; // 检查空指针

    int len = strlen(str); // 获取字符串长度
    int i;
    char temp;

    for (i = 0; i < len / 2; i++) {
        // 交换字符
        temp = str[i];
        str[i] = str[len - i - 1];
        str[len - i - 1] = temp;
    }

    return str;
}

int stack_peek(astack_t *s, char *tmp)
{
    if (astack_empty(s))
        return -1;

    astack_pop(s, tmp);
    astack_push(s, tmp);
}
